<template>
	<view class="container">
		<view class="title">密码登录</view>
		<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
			<view class="section">
				<view class="form">
					<view class="form-item">
						<view class="group" @click="isShowPopup = true">
							<view class="number">{{ areaCode }}</view>
							<view class="arrow">
								<image class="img" src="@/static/images/shape.png"></image>
							</view>
						</view>
						<view class="cell">
							<uni-forms-item required name="phone">
								<uni-easyinput
									v-model="formData.phone" placeholder="请输入手机号码"
									:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
								/>
							</uni-forms-item>
						</view>
					</view>
					<view class="form-item">
						<view class="cell">
							<uni-forms-item required name="password">
								<uni-easyinput
									type="password" v-model="formData.password" placeholder="请输入密码"
									:placeholderStyle="placeHolder.styles" :input-border="false" trim :clearable="false"
								/>
							</uni-forms-item>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="unit" @click="navigateTo('/pages/register/register')">注册</view>
					<view class="unit light" @click="navigateTo('/pages/register/reset')">忘记密码？</view>
				</view>
				<view class="actions">
					<z-button @click="submit">登录</z-button>
					<z-button type="plain" url="/pages/login/quickLogin">验证码快速登录</z-button>
				</view>
			</view>
		</uni-forms>
		<view class="footer">
			<view class="demerger">
				<view class="line"></view>
				<view class="context">第三方登录</view>
				<view class="line"></view>
			</view>
			<view class="logo">
				<image class="img" src="@/static/images/wechat.jpg"></image>
			</view>
		</view>
		<z-popup class="popup" v-model="isShowPopup" has-head title="地区选择" round="32rpx" @confirm="handleConfirm" @cancel="handleCancel">
			<picker-view indicator-style="height: 50px" :value="currentIndex" @change="handlePickerChange" class="picker-view">
				<picker-view-column>
					<view class="entry" v-for="(nation, index) in nations" :key="index">{{ nation }}</view>
				</picker-view-column>
			</picker-view>
		</z-popup>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { validatePhoneNumber, validatePassword } from '@/utils/validate'
import { clientLogin, getInfo } from '@/api/index'
import { navigateTo, switchTab } from '@/utils/navigator'
import { setToken } from '@/utils/auth'
import eventEmitter from '@/utils/eventEmitter'
import { CustomPlaceHoder } from '@/utils/common'

const placeHolder = new CustomPlaceHoder()
const formRef = ref()
const formData = reactive({
    phone: '12111111111',
    password: '12345a'
})
const rules = ref({
	phone: {
        rules: [
			{ required: true, errorMessage: '请输入手机号码' },
            { validateFunction: validatePhoneNumber }
		]
    },
	password: {
		rules: [
			{ required: true, errorMessage: '请输入密码' },
            { validateFunction: validatePassword }
		]
	}
})
const nations = ref(['+86 中国', '+60 马来西亚', '+07 俄罗斯', '+01 美国'])
const isShowPopup = ref(false)
const currentIndex = ref([0])
const areaCode = ref('+86')

const handleConfirm = () => {
	isShowPopup.value = false
	const match = nations.value[currentIndex.value].match(/^\+\d+/)
	areaCode.value = match ? match[0] : ''
}

const handleCancel = () => {
	isShowPopup.value = false
}

const handlePickerChange = ({ detail: { value } }) => {
	currentIndex.value = value
}

const submit = async () => {
	if (formRef.value) {
        const result = await formRef.value.validate().catch(() => false)
        if(result) {
			try {
				uni.showLoading({ title: '登录中', mask: true })
				const { phone: username, password } = formData
				const { code, msg, token } = await clientLogin({ username, password })
				if(code == 200) {
					token && setToken(token)
					const result = await getInfo()
					if(result && result.code == 200 && result.user) {
						result.storeId && (result.user.storeId = result.storeId)
						uni.setStorageSync('userInfo', JSON.stringify(result.user))
						eventEmitter.emit('STORAGE:USERINFO_CHANGE')
					} else {
						uni.showToast({ title: result?.msg || '获取用户信息失败', icon: 'none' })
					}
					// const { confirm } = await uni.showModal({
					// 	title: '提示',
					// 	content: '登录成功！',
					// 	showCancel: false,
					// 	confirmText: '确认'
					// }).catch(() => false)
					// if(confirm) {
					// 	switchTab('/pages/home/home')
					// }
					switchTab('/pages/home/home')
				} else {
					uni.showToast({ title: msg || '系统异常!', icon: 'none' })
				}
			} catch (error) {
				uni.showToast({ title: '登录失败，请重试', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		}
	}
}
</script>

<style lang="scss">
.container {
	background-color: #fff;
	height: 100vh;
	padding: 136rpx 32rpx 0 32rpx;
	font-family: PingFang SC, PingFang SC;
	.title {
		font-size: 44rpx;
		color: #222;
		font-weight: bold;
	}
	::v-deep .uni-forms {
        .uni-forms-item {
            margin-bottom: 0;
            &__label {
                display: none !important;
            }
            &__content {
                .uni-input-placeholder {
                    color: #BFBFBF;
                }
                .uni-forms-item__error {
					top: calc(100% + 8rpx);
                    text {
                        white-space: nowrap;
                    }
                }
				.uni-easyinput__content-input {
					padding: 0 !important;
					font-size: 32rpx;
				}
            }
        }
    }
	.section {
		margin-top: 32rpx;
		.form {
			margin-bottom: 24rpx;
			.form-item {
				display: flex;
				align-items: center;
				padding: 0 40rpx;
				height: 88rpx;
				border-radius: 44rpx;
				background-color: #F7F8FA;
				&:not(:last-child) {
					margin-bottom: 32rpx;
				}
				.group {
					display: flex;
					padding-right: 16rpx;
					border-right: 3rpx solid #E3E3E3;
					margin-right: 20rpx;
					.number {
						font-size: 32rpx;
						color: #000;
						margin-right: 4rpx;
					}
					.arrow {
						width: 24rpx;
						height: 12rpx;
						.img {
							height: 100%;
						}
					}
				}
				.cell {
					flex: 1;
				}
			}
		}
		.row {
			display: flex;
			justify-content: space-between;
			font-size: 28rpx;
			.unit {
				color: #666;
				&.light {
					color: #999;
				}
			}
		}
		.actions {
			margin-top: 32rpx;
			.btn-wrapper {
				margin-bottom: 24rpx;
			}
		}
	}
	.footer {
		position: fixed;
		bottom: 32rpx;
		left: 0;
		right: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		.demerger {
			display: flex;
			align-items: center;
			.line {
				width: 180rpx;
				height: 1rpx;
				background-color: #999;
			}
			.context {
				font-size: 28rpx;
				color: #999;
				margin: 30rpx;
			}
		}
		.logo {
			width: 88rpx;
			height: 88rpx;
			.img {
				height: 100%;
			}
		}
	}
	.popup {
		.picker-view {
			width: 100%;
			height: 400rpx;
			margin-top: 20rpx;
			.entry {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
}
</style>
